/**
 * @package platform
 * @description 定义平台基础服务，兼容CMD、AMD规范
 */
!(function (factory) {
    if (typeof require === 'function' && typeof exports === 'object' &&
        typeof module === 'object') {
        var target = module['exports'] || exports;
        factory(target);
    } else if (typeof define === 'function' && define['amd']) {
        define(['exports'], factory);
    } else {
        factory(window['platform'] = {});
    }
})(function (platformExports) {
    var platform = typeof platformExports !== 'undefined' ? platformExports : {};
    /**
     * @method trim
     * @description 去除尾部空格
     */
    platform.trim = function (str) {
        return str.replace(/(^\s*)|(\s*$)/g, '');
    };
    /**
     * @method trimAll
     * @description 去除全部空格
     */
    platform.trimAll = function (str) {
        return str.replace(/(^\s+)|(\s+$)/g, '').replace(/\s/g, '');
    };
    /**
     * @method random16Key
     * @description 生成16位随机字符串
     */
    platform.random16Key = function () {
        var res = '';
        var chars = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J',
            'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U',
            'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f',
            'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q',
            'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1',
            '2', '3', '4', '5', '6', '7', '8', '9'
        ];
        for (var i = 0; i < 16; i++) {
            var id = Math.ceil(Math.random() * 63);
            res += chars[id];
        }
        return res;
    };
    /**
     * @method aesEncrypt
     * @description 默认加密
     */
    platform.aesEncrypt = function (data) {
        var sendData = CryptoJS.enc.Utf8.parse(data);
        var key = CryptoJS.enc.Utf8.parse('1QAZ2wsx3EDC4rfv');
        var iv = CryptoJS.enc.Utf8.parse('5tgb6YHN7ujm8IKL');
        var encrypted = CryptoJS.AES.encrypt(sendData, key, {
            iv: iv,
            mode: CryptoJS.mode.CBC,
            padding: CryptoJS.pad.Pkcs7
        });
        return CryptoJS.enc.Base64.stringify(encrypted.ciphertext);
    };
    /**
     * @method aesRandomEncrypt
     * @description 随机密钥，AES加密
     */
    platform.aesRandomEncrypt = function (data) {
        var sendData = CryptoJS.enc.Utf8.parse(data);
        var key = CryptoJS.enc.Utf8.parse(this.random16Key());
        var iv = CryptoJS.enc.Utf8.parse(this.random16Key());
        var encryptStr = CryptoJS.AES.encrypt(sendData, key, {
            iv: iv,
            mode: CryptoJS.mode.CBC,
            padding: CryptoJS.pad.Pkcs7
        });
        return {
            keyt: {
                key: key,
                iv: iv
            },
            encrypt: encryptStr
        }
    };
    // AES解密
    platform.aesDecrypt = function (data) {
        var encrypt = CryptoJS.enc.Hex.parse(data);
        var key = CryptoJS.enc.Utf8.parse('1QAZ2wsx3EDC4rfv');
        var iv = CryptoJS.enc.Utf8.parse('5tgb6YHN7ujm8IKL');
        var encrypted = CryptoJS.AES.decrypt(CryptoJS.enc.Base64
            .stringify(encrypt), key, {
            iv: iv,
            mode: CryptoJS.mode.CBC,
            padding: CryptoJS.pad.Pkcs7
        });
        var decryptedStr = encrypted.toString(CryptoJS.enc.Utf8);
        return decryptedStr.toString();
    };
    platform.mapUrl = function (url) {
        // var location = (window.location + '').split('/');
        // console.log(location);
        // var baseUrl = location[0] + '//' + location[2] + '/' +
        //     location[3];
        // if (url == null || url == undefined) {
        //     return baseUrl;
        // } else {
        //     return baseUrl + url.replace('~', '');
        // }
        return url.replace('~', '');
    };
    /**
     * 同步调用
     * @param url
     * @param param
     * @param fnSendBefore
     */
    platform.servicebreak = function (url, param, fnSendBefore) {
        var p = param === undefined ? {} : param;
        if ($.cookie('tokenId') !== undefined) {
            p.tokenId = $.cookie('tokenId');
        }


        return $.ajax({
            type: 'post',
            url: this.mapUrl(url),
            contentType: 'application/json',
            dataType: 'json',
            async: false,
            data: JSON2.stringify(p),
            beforeSend: fnSendBefore || function () {
            }
        }).done(function (response) {
            return response;
        });
    };
    platform.servicebreakYzw = function (url, param) {
        return $.ajax({
            type: 'post',
            url: this.mapUrl(url),
            contentType: 'application/json',
            dataType: 'json',
            async: false,
            data: JSON2.stringify(param === null ? {} : param)
        }).done(function (response) {
            return response;
        });
    };
    /**
     * 异步调用Rest
     * @param url
     * @param param
     * @param method
     * @param fnSendBefore
     */
    platform.servicebreakAsync = function (url, param, method, fnSendBefore) {
        var p = param === undefined ? {} : param;
        if ($.cookie('tokenId') !== undefined) {
            p.tokenId = $.cookie('tokenId');
        }

        return $.ajax({
            type: method || 'post',
            url: this.mapUrl(url),
            contentType: 'application/json',
            dataType: 'json',
            data: JSON2.stringify(p),
            async: true,
            beforeSend: fnSendBefore || function () {
            }
        }).then(function (response) {
            return response;
        }, function (error) {
            return error;
        });
    };
    platform.servicebreakAsyncNoMap = function (url, param, method, fnSendBefore) {
        return $.ajax({
            type: method || 'post',
            url: url,
            contentType: 'application/json',
            dataType: 'json',
            data: JSON2.stringify(param === null ? {} : param),
            async: true,
            beforeSend: fnSendBefore || function () {
            }
        }).then(function (response) {
            return response;
        }, function (error) {
            return error;
        });
    };
    /**
     * 获取UUID
     */
    platform.uuid = function () {
        var uuid = '';
        $.ajax({
            type: 'post',
            url: this.mapUrl('~/rest/uuid'),
            async: false
        }).done(function (response) {
            uuid = response;
        });
        return uuid;
    };
    platform.log = function (str) {
        if (window.console) {
            window.console.log(str);
        }
    };
    /**
     * 获取当前用户
     */
    platform.getCurrentUser = function () {
        var user;
        this.servicebreak('~/rest/getCurrentUserInfo').done(
            function (response) {
                user = response;
            });
        return user;
    };

    /**
     *
     * @param parentId
     */
    platform.getPubCode = function (parentId) {
        return this.servicebreak('~/rest/getPubCodeById', {pid: parentId}).responseJSON;
    };
    platform.encode = function (str) {
        return encodeURIComponent(encodeURIComponent(str));
    };
    platform.exportExcel = function (params) {
        var args = {};
        args.param = this.encode(JSON2.stringify(params));

        var pattern = "";
        for (var key in args) {
            if (pattern == "") {
                pattern += key + "=" + args[key];
            } else {
                pattern += "&" + key + "=" + args[key];
            }
        }

        window.open(this.mapUrl("~/rest/excel/exportExcel") + ("?" + pattern), "_blank");
    };
    // 信息提示部分
    platform.showErrorTip = function (msg) {
        $.ikg_showtip(msg, $.ikg_showtip.TYPE_ERROR);
    };
    platform.showWarnTip = function (msg) {
        $.ikg_showtip(msg, $.ikg_showtip.TYPE_WAR);
    };
    platform.showOkTip = function (msg) {
        $.ikg_showtip(msg, $.ikg_showtip.TYPE_OK);
    };
    platform.showTip = function (type) {
        if (type === undefined || type === null) {
            this.showErrorTip('未指定操作类型!');
            return;
        }
        switch (type.toUpperCase()) {
            case 'EDIT':
                this.showWarnTip('请选择至多一行数据进行编辑!');
                break;
            case 'REMOVE':
                this.showWarnTip('请选择至多一行数据进行删除!');
                break;
            case 'REMOVEMULTI':
                this.showWarnTip('请选择至少一行数据进行删除!');
                break;
            case 'VIEW':
                this.showWarnTip('请选择至多一行数据进行查看!');
                break;
            case 'MOVE':
                this.showWarnTip('请选择至多一行数据进行移动!');
                break;
            case 'GRANT':
                this.showWarnTip('请选择至多一行数据进行授权!');
                break;
            case 'CALCULATE':
                this.showWarnTip("请选择至多一行数据进行计算!");
                break;
            case 'EXPORTEXCELL':
                this.showWarnTip("请选择至多一行数据进行导出!");
                break;
        }
    };
    platform.showOperTip = function (operType) {

        if (operType === undefined || operType === null) {
            this.showErrorTip('未指定操作类型!');
            return;
        }
        var type = operType.toUpperCase();
        switch (type) {
            case 'SAVESUC':
                this.showOkTip('保存成功!');
                break;
            case 'SAVEFAIL':
                this.showErrorTip('保存失败!');
                break;
            case 'SAVELOADING':
                this.showOkTip('<i class="fa fa-spinner fa-spin"></i>&nbsp;&nbsp;数据保存中....');
                break;
            case 'DELSUC':
                this.showOkTip('删除成功!');
                break;
            case 'DELFAIL':
                this.showErrorTip('删除失败!');
                break;
            case 'VALIDATEFAIL':
                this.showWarnTip('未通过系统校验,请重新核对数据...');
                break;
            case 'VALIDATING':
                this.showOkTip('<i class="fa fa-spinner fa-spin"></i>&nbsp;&nbsp;用户信息校验中...');
                break;
            case 'GRANTSUC':
                this.showOkTip('授权成功!');
                break;
            case 'GRANTFAIL':
                this.showErrorTip('授权失败');
                break;
            case 'DEALING':
                this
                    .showOkTip('<i class="fa fa-spinner fa-spin"></i>&nbsp;&nbsp;业务处理中...');
                break;
        }
    };
    platform.forbiddenEnter = function (e) {
        var ev = (typeof event !== 'undefined') ? window.event : e;
        if (ev.keyCode === 13 && document.activeElement.id === "msg") {
            return false; // 禁用回车事件
        }
    };
    platform.removeEmptyNode = function (nodes) {
        $.each(nodes, function (n, node) {
            if (node.nodes === null)
                return;
            if (node.nodes.length === 0) {
                delete node.nodes;
            } else {
                platform.removeEmptyNode(node.nodes);
            }
        });
    };
});
(function ($) {
    $.fn.resetForm = function () {
        $(this)[0].reset();

        var arrDoms = $(".form-control");
        for (var i in arrDoms) {
            arrDoms[i].disabled = false;
        }
    };
    $.fn.disableForm = function () {
        $(this)[0].find('input,textarea,select').attr('disabled', true);
    };
    $.fn.enableForm = function () {
        $(this)[0].find('input,textarea,select').attr('disabled', false);
    };
})(jQuery);